<template>
  <div class="menu-management">
    <!-- 操作按钮区域 -->
    <div class="right-buttons">
      <el-button type="primary" icon="Plus" @click="openAddDialog">
        添加菜单
      </el-button>
    </div>

    <!-- 表格容器 -->
    <el-table
      :data="tableData"
      style="width: 100%; margin-bottom: 20px"
      row-key="menuId"
      border
      :tree-props="treeProps"
    >
      <el-table-column prop="menuId" label="菜单编号" width="80px" align="center" />
       <el-table-column prop="parentId" label="父级菜单"  >
        <template #default="scope">
          <el-tag v-if="scope.row.parentId === 0" type="success">一级菜单</el-tag>
          <el-tag v-else>二级菜单</el-tag>
        </template>
       </el-table-column>
      <el-table-column prop="meta.icon" label="菜单图标">
        <template #default="scope">
          <el-icon :class="scope.row.meta.icon" v-if="scope.row.meta.icon" >
            <!-- 动态标签样式 -->
            <component
              :is="scope.row.meta.icon"
            />
            </el-icon>
          <span v-else>无</span>
        </template>
      </el-table-column>
      <el-table-column prop="meta.title" label="菜单标题"  />
      <el-table-column prop="name" label="菜单名称"  />
      <el-table-column prop="path" label="路径地址"  />
      <el-table-column prop="component" label="组件路径"  />
      <el-table-column prop="meta.noCache" label="缓存状态"  >
        <template #default="scope">
          <el-tag :type="scope.row.meta.noCache ? 'danger' : 'success'">
            {{ scope.row.meta.noCache ? '不缓存' : '缓存' }}
          </el-tag>
        </template>
      </el-table-column>
      


      <!-- <el-table-column prop="externalLinks" label="是否外链">
        <template #default="scope">
          <el-switch
            v-model="scope.row.externalLinks"
            inline-prompt
            active-value="1"
            inactive-value="0"
            active-text="是"
            inactive-text="否"
            disabled
          />
        </template>
      </el-table-column> -->
      <!-- <el-table-column prop="orderItem" label="排序"  /> -->
      <el-table-column label="操作"  width="100px" fixed="right" >
        <template #default="scope">
          <el-button size="small" type="primary" :icon="Edit" circle @click="handleEdit(scope.row)"></el-button>
          <el-button size="small" type="danger" :icon="Delete" circle @click="handleDelete(scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增菜单弹窗 -->
    <el-dialog
      v-model="addDialogVisible"
      :title="isAdd ? '新增菜单' : '编辑菜单'"
      width="500px"
      :close-on-click-modal="false"
      draggable
    >
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="addFormRules"
        label-width="100px"
        class="add-form"
      >
        <!-- <el-form-item label="上级菜单" prop="parentId">
          <el-select
            v-model="addForm.parentId"
            placeholder="请选择上级菜单"
            clearable
          >
            <el-option label="顶级菜单" value="0" />
           
            <template v-for="menu in tableData" :key="menu.menuId">
              <el-option
                :label="menu.menuTitle"
                :value="menu.menuId"
              />
              <template v-if="menu.subMenu && menu.subMenu.length">
                <el-option
                  v-for="subMenu in menu.subMenu"
                  :key="subMenu.menuId"
                  :label="`└─ ${subMenu.menuTitle}`"
                  :value="subMenu.menuId"
                />
              </template>
            </template>
          </el-select>
        </el-form-item> -->
        <el-form-item label="菜单名称" prop="name">
          <el-input
            v-model="addForm.name"
            placeholder="请输入菜单名称"
            maxlength="50"
          />
        </el-form-item>

        <el-form-item label="菜单标题" prop="meta.title">
          <el-input
            v-model="addForm.meta.title"
            placeholder="请输入菜单标题"
            maxlength="50"
          />
        </el-form-item>

         <el-form-item label="菜单图标" prop="meta.icon">
          <el-input
            v-model="addForm.meta.icon"
            placeholder="输入Element图标类名(如:Setting)"
            maxlength="50"
          />
          <el-text type="info" size="small" class="form-hint">
            图标参考：<a href="https://element-plus.org/zh-CN/component/icon.html" target="_blank">Element Plus图标库</a>
          </el-text>
        </el-form-item>

        <el-form-item label="路径地址" prop="path">
          <el-input
            v-model="addForm.path"
            placeholder="请输入路径地址（如：/study-room)"
            maxlength="100"
          />
        </el-form-item>
         <el-form-item label="组件路径" prop="component">
          <el-input
            v-model="addForm.component"
            placeholder="请输入组件路径（如：@/views/study-room/Index.vue)"
            maxlength="100"
          />
        </el-form-item>

       
        <!-- <el-form-item label="组件路径" prop="menuCurl">
          <el-input
            v-model="addForm.menuCurl"
            placeholder="组件在@/components下的路径;是外链不用填！"
            maxlength="100"
          />
          <el-text type="info" size="small" class="form-hint">
            用于动态路由加载组件
          </el-text>
        </el-form-item>

        <el-form-item label="是否外链" prop="externalLinks">
          <el-radio-group v-model="addForm.externalLinks">
            <el-radio label="0">否（内部路由）</el-radio>
            <el-radio label="1">是（外部链接）</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="排序号" prop="orderItem">
          <el-input
            v-model.number="addForm.orderItem"
            type="number"
            placeholder="数字越小越靠前"
            min="0"
            max="999"
          />
        </el-form-item> -->
      </el-form>

      <template #footer>
        <el-button @click="resetAddForm">取消</el-button>
        <el-button type="primary" @click="submitAddForm">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {
  Delete,
  Edit,
} from '@element-plus/icons-vue'
import { ref, reactive, onMounted, nextTick } from 'vue';
import { ElMessage, ElForm, ElFormItem, ElInput, ElSelect, ElOption, ElRadioGroup, ElRadio } from 'element-plus';
 
import type { FormInstance, FormRules } from 'element-plus';
import { selectAllMenus } from '@/api/menu';
import {useUserStore} from '@/stores/modules/user';
import { insertMenu } from '@/api/menu';
import { editMenu } from '@/api/menu';
import { useRouter } from 'vue-router';
const router = useRouter();
const userStore = useUserStore();

// 菜单数据类型定义
interface Menu {
  menuId: number;
  parentId: number;
  name: string;
  path: string;
  redirect?: string;
  component: string;
  query?: string;
  alwaysShow?: boolean;
  meta: {
    title: string;
    icon?: string;
    noCache: boolean;
    link?: string;
  };
  children: Menu[];
}

// 新增表单数据类型（排除只读字段）
interface AddMenuForm {
  parentId: string | number; // 支持字符串/数字类型的ID
  menuId: number;
  name: string;
  path: string;
  component: string;
  meta: {
    title: string;
    icon?: string;
    noCache: boolean;
    link?: string;
  };
}

// 表格数据
const tableData = ref<Menu[]>([]);

// 树形表格配置
const treeProps = reactive({
  children: 'children',
  hasChildren: 'hasChildren'
});

// 新增弹窗状态
const addDialogVisible = ref(false);
const isAdd = ref(true); // true:新增 false:编辑
// 新增表单数据
const addForm = ref<AddMenuForm>({
  parentId: 0, // 默认顶级菜单
  menuId: 0,
  name: '',
  path: '',
  component: '',
  meta: {
    title: '',
    icon: '',
    noCache: false,
    link: ''
  }
});

// 表单引用
const addFormRef = ref<FormInstance>();
const currentMenuId = ref<number | null>(null);
// 新增表单验证规则
const addFormRules = reactive<FormRules<AddMenuForm>>({
  name: [
    { required: true, message: '请输入菜单名称', trigger: 'blur' },
    { min: 1, max: 50, message: '菜单名称长度在1-50个字符之间', trigger: 'blur' }
  ],
  path: [
    { required: true, message: '请输入路径地址', trigger: 'blur' },
  ],
  'meta.title': [
    { required: true, message: '请输入菜单标题', trigger: 'blur' },
  ],
});

// 页面加载时获取菜单列表
onMounted(() => {
  fetchMenuList();
  
});

// 获取菜单列表数据
const fetchMenuList = async () => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录');
    router.push('/home');
    return;
  }
  try {
     const username = userStore.currentUser.username;
     console.log("当前用户名:", username);
     
   const res= await selectAllMenus()  
    console.log("获取菜单列表成功:", res);
   
    
    
      if(res.code == 200){
        tableData.value = res.data
      }else {
      ElMessage.error('加载菜单失败：' + (res.msg || '未知错误'));
    }
    } catch (err) {
    console.error('获取菜单列表异常：', err);
    ElMessage.error('网络错误，无法加载菜单列表');
  }
};

// 打开新增弹窗
const openAddDialog = () => {
  addDialogVisible.value = true;
  isAdd.value = true; // true:新增 false:编辑
  // 重置表单
  nextTick(() => {
    addFormRef.value?.resetFields();
    // 重置默认值
    addForm.value = {
      parentId: 0,
      menuId: 0,
      name: '',
      path: '',
      component: '',
      meta: {
        title: '',
        icon: '',
        noCache: false,
        link: ''
      }
    };
  });
};

// 重置表单
const resetAddForm = () => {
  addFormRef.value?.resetFields();
  addDialogVisible.value = false;
};

// 提交新增编辑的表单
const submitAddForm = async () => {
  if (!addFormRef.value) return;

  try {
    // 表单验证
    await addFormRef.value.validate();
    //获取用户名
    const username = userStore.currentUser.username;

    // 准备提交数据（转换parentId为数字）
    const submitData = {
      ...addForm.value,
      username: username,
    };
    console.log(submitData);
    if(isAdd.value){
      // 调用新增接口
      const res = await insertMenu(submitData);
      if (res.code === 200) {
        ElMessage.success('菜单新增成功！');
        addDialogVisible.value = false;
        // 重新加载菜单列表
        fetchMenuList();
      } else {
        ElMessage.error('新增失败：' + (res.msg || '服务器处理失败'));
      }
    }else{
        // 调用编辑接口
      const res = await editMenu(submitData);
      if (res.code === 200) {
        ElMessage.success('菜单编辑成功！');
        addDialogVisible.value = false;
        // 重新加载菜单列表
        fetchMenuList();
      } else {
        ElMessage.error('编辑失败：' + (res.msg || '服务器处理失败'));
      }
    }
  } catch (error) {
    console.error('新增菜单失败：', error);
    // 表单验证失败不提示错误（由组件自行提示）
    if (!(error instanceof Error && error.message.includes('Validation failed'))) {
      ElMessage.error('操作失败，请稍后重试');
    }
  }
};

// 编辑菜单（保留方法，与新增功能区分）
const handleEdit = (menu: Menu) => {
  isAdd.value = false; // true:新增 false:编辑
 // 复制菜单数据到表单
  addForm.value = {
    menuId: menu.menuId,
    parentId: menu.parentId,
    name: menu.name,
    path: menu.path,
    component: menu.component,
    meta: {
      title: menu.meta.title,
      icon: menu.meta.icon || '',
      noCache: menu.meta.noCache,
      link: menu.meta.link || ''
    }
  };
  currentMenuId.value = menu.menuId;
  addDialogVisible.value = true;
};

// 删除菜单（保留方法）
const handleDelete = (menu: Menu) => {
  ElMessage.info('删除功能暂不实现，以免误删！');
};
</script>

<style scoped>
.right-buttons {
  margin-bottom: 16px;
  text-align: right;
}

.add-form {
  margin-top: 20px;
}

.el-form-item__error {
  padding-top: 4px;
  font-size: 12px;
}

::v-deep .el-select-dropdown__item {
  white-space: nowrap;
}

.form-hint {
  margin-top: 6px;
  display: block;
}
</style>